package com.cershy.chatroomserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cershy.chatroomserver.dto.CreateGroupRequest;
import com.cershy.chatroomserver.entity.Group;
import com.cershy.chatroomserver.entity.UserList;
import com.cershy.chatroomserver.mapper.GroupMapper;
import com.cershy.chatroomserver.mapper.UserListMapper;
import com.cershy.chatroomserver.service.UserListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserListServiceImpl extends ServiceImpl<UserListMapper, UserList> implements UserListService {

    private static final Logger log = LoggerFactory.getLogger(UserListServiceImpl.class); // 使用 SLF4J Logger
    @Autowired
    private UserListMapper userListMapper;

    @Override
    public List<UserList> getGroupsByUserId(String userId) {
        return userListMapper.selectList(new QueryWrapper<UserList>().eq("user_id", userId));
    }

    @Override
    public boolean isUserInGroup(String userId, String groupId) {
        return userListMapper.selectOne(new QueryWrapper<UserList>()
                .eq("user_id", userId)
                .eq("group_id", groupId)) != null;
    }

    @Transactional
    @Override
    public boolean addUserToGroup(String userId, String groupId, String role) {
        log.info("开始加入群聊：用户ID={}, 群组ID={}, 角色={}", userId, groupId, role);

        // 1. 检查是否已存在
        if (isUserInGroup(userId, groupId)) {
            log.warn("用户 {} 已加入群组 {}", userId, groupId);
            return false;
        }

        // 2. 设置默认角色
        if (role == null || role.isEmpty()) {
            role = "user";
            log.debug("角色未指定，使用默认角色: user");
        }

        // 3. 构造实体
        UserList userList = new UserList();
        userList.setId(java.util.UUID.randomUUID().toString());
        userList.setUserId(userId);
        userList.setGroupId(groupId);
        userList.setRole(role);
        userList.setCreateTime(new java.util.Date());
        userList.setUpdateTime(new java.util.Date());

        // 4. 插入数据库
        try {
            int rowsAffected = userListMapper.insert(userList);
            if (rowsAffected > 0) {
                log.info("用户 {} 成功加入群组 {}，受影响行数: {}", userId, groupId, rowsAffected);
                return true;
            } else {
                log.error("用户 {} 加入群组 {} 失败，受影响行数为 0", userId, groupId);
                return false;
            }
        } catch (Exception e) {
            log.error("用户 {} 加入群组 {} 时发生异常", userId, groupId, e);
            throw e; // 重新抛出以便事务回滚
        }
    }




    @Override
    public List<String> getGroupIdsByUserId(String userId) {
        LambdaQueryWrapper<UserList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserList::getUserId, userId);
        return this.list(wrapper)
                .stream()
                .map(UserList::getGroupId)
                .collect(Collectors.toList());
    }
    @Override
    public String getGroupOwnerId(String groupId) {


        // 使用 LambdaQueryWrapper 构建查询条件，避免字段名拼写错误
        UserList userList = userListMapper.selectOne(new LambdaQueryWrapper<UserList>()
                .eq(UserList::getGroupId, groupId)
                .eq(UserList::getRole, "leader"));

        // 如果查询结果为空，打印警告日志
        if (userList == null) {
            log.warn("No group owner found for group ID: {}", groupId);
            return null;
        }

        return userList.getUserId();
    }

    @Override
    public List<Map<String, Object>> getGroupUsers(String groupId) {
        return userListMapper.selectGroupUsers(groupId);
    }


    @Autowired
    private GroupMapper groupMapper;

    @Override
    @Transactional
    public boolean createGroup(CreateGroupRequest request) {
        log.info("开始创建群聊: {}", request);

        // 1. 生成 group_id
        String groupId = generateGroupId();
        log.debug("生成群ID: {}", groupId);

        // 2. 插入到 group 表
        Group group = new Group();
        group.setId(groupId);
        group.setName(request.getName());
        group.setAvatar(request.getAvatar());
        group.setLeader(request.getLeader());
        group.setLeaderId(request.getLeaderId());

        int groupInserted = groupMapper.insert(group);
        if (groupInserted <= 0) {
            log.error("插入群表失败");
            return false;
        }

        // 3. 插入到 user_list 表，设置群主
        UserList userList = new UserList();
        userList.setId(java.util.UUID.randomUUID().toString());
        userList.setUserId(request.getLeaderId());
        userList.setGroupId(groupId);
        userList.setRole("leader");

        int userInserted = userListMapper.insert(userList);
        if (userInserted <= 0) {
            log.error("插入用户-群关系失败");
            throw new RuntimeException("插入用户-群关系失败");
        }

        log.info("群聊创建成功: {}", groupId);
        return true;
    }

    // 生成 group_id 方法
    private String generateGroupId() {
        long groupNumber = System.currentTimeMillis() % 10000000000L; // 取后10位时间戳
        return "group_" + String.format("%010d", groupNumber);
    }

    @Override
    public boolean removeUserFromGroup(String userId, String groupId) {
        return userListMapper.deleteByUserIdAndGroupId(userId, groupId) > 0;
    }


    @Override
    public boolean disbandGroup(String groupId, String ownerId) {
        try {
            // 1. 获取所有群成员
            List<String> members = userListMapper.selectUserIdsByGroupId(groupId);
            if (members == null || members.isEmpty()) {
                log.warn("群聊 {} 中无成员", groupId);
            } else {
                // 2. 移除所有成员（包括自己）
                for (String userId : members) {
                    removeUserFromGroup(userId, groupId);
                }
            }

            int rowsDeleted = groupMapper.deleteById(groupId);
            if (rowsDeleted > 0) {
                log.info("群聊 {} 成功解散", groupId);
                return true;
            } else {
                log.warn("群聊 {} 解散失败，未找到该群", groupId);
                return false;
            }
        } catch (Exception e) {
            log.error("解散群聊失败", e);
            return false;
        }
    }
}
